import requests
import json

def get_public_ip():
    """获取本机的公网IP地址"""
    try:
        response = requests.get('https://www.ipplus360.com/getIP')
        if response.status_code == 200:
            return response.json().get('data')
        else:
            return None
    except Exception as e:
        print(f"Failed to get public IP: {e}")
        return None

def get_geo_info(ip_address):
    """根据IP地址获取地理位置信息"""
    try:

        response = requests.get(f'http://whois.pconline.com.cn/ipJson.jsp?ip={ip_address}&json=true')
        if response.status_code == 200:
            return response.json()
        else:
            return None
    except Exception as e:
        print(f"Failed to get geo info: {e}")
        return None

def get_ip_and_geo():
    """获取IP地址和地理位置信息"""
    ip_address = get_public_ip()
    if ip_address:
        geo_info = get_geo_info(ip_address)
        return {
            'ip': ip_address,
            'geo': geo_info
        }
    return None

# 示例用法
if __name__ == "__main__":
    result = get_ip_and_geo()
    if result:
        print(result)
        print(f"IP Address: {result['ip']}")
        print(f"Geo Info: {json.dumps(result['geo'], indent=4)}")
    else:
        print("Failed to retrieve IP and geo information.")